package ypmits.components.modal {
	import ypmits.components.Component;
	import ypmits.components.ComponentSkin;
	import ypmits.setup.EasySetup;

	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;

	/**
	 * @author Dave Lenz
	 */
	public class Modal extends Component implements IModal {

		protected var back : Sprite;
		protected var graphic : Sprite;

		
		
		/**
		 * Use 'head' and 'body' to set the text, setSize() to set the size, and then show() to show the modal!
		 */
		public function Modal( skin : ComponentSkin, clickanywheretoclose : Boolean = false ) {
			!skin ? skin = new ComponentSkin() : null;
			skin.clickanywheretoclose = clickanywheretoclose;

			super( skin );
			
			draw( );
			
			EasySetup.instance.stage.addEventListener( Event.RESIZE, resizeHandler );
		}

		
		override public function validate() : Boolean {
			return true;
		}

		
		override public function dispose() : void {
		}

		
		protected function draw() : void {
			addChild( back = new Sprite() );
			addChild( graphic = new Sprite() );
			if( skin.clickanywheretoclose ) addEventListener(MouseEvent.CLICK, closeClickHandler );
			redraw();
			
			visible = false;
			alpha = 0;
		}

		
		private function redraw() : void {
			var sw : Number = EasySetup.instance.stage.stageWidth;
			var sh : Number = EasySetup.instance.stage.stageHeight;
			
			back.graphics.clear( );
			back.graphics.beginFill( skin.backgroundcolor, skin.backgroundalpha );
			back.graphics.drawRect( 0, 0, sw, sh );
			back.graphics.endFill( );
			
			graphic.x = sw * .5;
			graphic.y = sh * .5;
		}

		
		private function closeClickHandler( e : MouseEvent ) : void {
			hide( );
			
			dispatchEvent( new Event( Event.CLOSE ) );
		}

		
		override public function show() : void {
			alpha = 1;
			visible = true;
		}

		
		protected function showDone() : void {
		}

		
		override public function hide() : void {
			alpha = 0;
			visible = false;
		}

		
		protected function hideDone() : void {
		}
		
		
		
		public function centerGraphic( _graphic : DisplayObject ) : void
		{
			_graphic.x = -(_graphic.width * .5);
			_graphic.y = -(_graphic.height * .5);
			graphic.addChild( _graphic );
		}

		
		
		private function resizeHandler( e : Event ) : void 
		{
			redraw();
		}
	}
}
